# from concurrent.futures import ThreadPoolExecutor
# from time import sleep


# def some_func(arg):
#     print(arg)
#     sleep(10)


# with ThreadPoolExecutor(max_workers=10) as executor:
#     for arg in range(10000000):
#         future = executor.submit(some_func, arg)


from concurrent.futures import ThreadPoolExecutor, as_completed
import os
import time
from random import randint


def test(num):
    for _ in range(2):
        time.sleep(randint(1, 5))  # 设置随机等待时间，
    return num


if __name__ == "__main__":
    max_pool = os.cpu_count() * 4  # 线程池最大线程数
    executor = ThreadPoolExecutor(max_workers=max_pool)
    all_task = []
    for i in range(1000000):  # 假设任务规模为50, 当然实际可能有上百上千万
        if len(all_task) < max_pool:
            all_task.append(executor.submit(test, i))
            print("创建：", i)
        else:
            for future in as_completed(all_task):
                all_task.remove(future)
                all_task.append(executor.submit(test, i))
                print("完成：", future.result(), "   创建：", i)
                break
    for future in as_completed(all_task):
        print("完成：", future.result())
